package youtube.tv.authentication

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import org.springframework.web.context.request.RequestContextHolder

/**
 * @author Sergey Istomin
 */
class AuthenticationService {

    def grailsApplication
    def socialAuthenticationService
    UserService googleAutenticationService = UserServiceFactory.userService

    Boolean isLoggedIn() {
        return socialAuthenticationService.isLoggedIn() || googleAutenticationService.currentUser != null
    }
    
    AppUser getUser() {
        def session = RequestContextHolder.currentRequestAttributes()?.session
        if (session.userId) {
            return new AppUser(userId: session.userId)
        }
        AppUser user = socialAuthenticationService.getUser()
        if (!user && googleAutenticationService.currentUser) {
            user = new AppUser(userId: googleAutenticationService.currentUser.email)
        }

        if(user) {
            session.userId = user.userId
        }
        return user
    }



}
